package com.zk.server.controller;

import com.google.common.io.BaseEncoding;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/")
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getHomePage(Model model) {
        Map<String, String> classLoaderMap = new LinkedHashMap<>(8);

        ClassLoader guavaLibClassLoader = BaseEncoding.class.getClassLoader();
        classLoaderMap.put("Guava.jar#BaseEncoding#ClassLoader", String.valueOf(guavaLibClassLoader));

        ClassLoader objectClassLoader = Object.class.getClassLoader();
        classLoaderMap.put("Object.class#ClassLoader", String.valueOf(objectClassLoader));

        ClassLoader stringClassLoader = String.class.getClassLoader();
        classLoaderMap.put("String.class#ClassLoader", String.valueOf(stringClassLoader));

        ClassLoader homeControllerClassLoader = HomeController.class.getClassLoader();
        classLoaderMap.put("HomeController#ClassLoader", String.valueOf(homeControllerClassLoader));

        String guavaPomPropertiesContent = readResources(getInputStream(guavaLibClassLoader, "META-INF/maven/com.google.guava/guava/pom.properties"));
        classLoaderMap.put("Guava.jar#pom.properties", guavaPomPropertiesContent);

        String guavaBaseEncodingClazzContent = readResources(getInputStream(BaseEncoding.class, "BaseEncoding.class"));
        classLoaderMap.put("Guava.jar#BaseEncoding.class", guavaBaseEncodingClazzContent);

        model.addAttribute("classLoaderMap", classLoaderMap);

        return "home";
    }

    private String readResources(InputStream inputStream) {
        String content = null;
        try {
            content = IOUtils.toString(inputStream, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return content;
    }

    protected InputStream getInputStream(ClassLoader classLoader, String filePath) {
        return classLoader.getResourceAsStream(filePath);
    }

    protected InputStream getInputStream(Class<?> clazz, String filePath) {
        return clazz.getResourceAsStream(filePath);
    }

}